package server.processors;

import java.nio.channels.ClosedChannelException;

import server.NetworkMediator;
import server.ServerStateMediator;

import common.Auction;
import common.AuctionExpiration;
import common.Player;
import common.Sendable;

public class AuctionCancellationProcessor extends Processor {

	public AuctionCancellationProcessor(){}
	
	public AuctionCancellationProcessor( NetworkMediator mediator, ServerStateMediator server ) {
		super( mediator, server );
	}
	
	@Override
	public Processor getInstanceOf(NetworkMediator mediator,
			ServerStateMediator server) {
		return new AuctionCancellationProcessor( mediator, server );
	}

	@Override
	public boolean isInterestedIn(Sendable s) {
		return s instanceof AuctionExpiration;
	}

	public void run() {
		//This auction could have already been removed if successfully matched before expiration
		// but it is still safe to do anyways.
		
		NetworkMediator network = getNetwork();
		
		Player player = getServer().sentBy();
		AuctionExpiration message = (AuctionExpiration) getServer().getMessage();
		
		Auction auction = message.expired;
		
		if( player.removeAuction( auction ) ) {
			// if it actually was removed, aka expired successfully
			// send a packet to the client telling it about the expiration
			
			//Remove the Expiration event that is also scheduled.
			auction.cancelExpiration();
			
			try {
				//Tell all players in the round about the expired auction.
				network.sendToAllInRound( player.getRound(), new AuctionExpiration( auction ) );
//				network.sendTo(player, new AuctionExpiration( auction ) );
			} catch (ClosedChannelException e) {
				e.printStackTrace();
			}
		}
	}

}
